local cjson  = require "cjson.safe"

local DEF  = require "proxy.game.common.def"
local ngx  = _G.ngx


local ContentDecoders = {
  gzip = {
    decode = function(data)
      local zlib = require("zlib")
      local stream = zlib.inflate()
      local r = stream(data)

      return cjson.decode(r)
    end
  }
}


local _M = {}
do
  function _M.get_method(req)
    local method
    do
      local headers, err = req.get_headers()
      if not err  and  type(headers)=='table' then
        method = headers['X-Http-Method']
      end
    end

    if not method then
      return req.get_method()
    end
    return method
  end

  function _M.get_response_spec(service, action, method)
    local node = DEF
    for _, v in ipairs({service, action, method}) do
      node = node[v]
      if node == nil then
        return node
      end
    end
    return node.response
  end

  function _M.fill_response_header(headers)
    if type(headers) == 'table' then
      for k, v in pairs(headers) do
        if k ~= 'Server' then
          ngx.header[k] = v
        end
      end
    end
  end

  --[[
    arguments
      resp {
        status  (number) : The resonse status, e.g. 200
        headers (table)  : A Lua table with response headers.
        body    (string) : The plain response body
      }
      content_type (string)
  ]]
  function _M.is_match_content_type(resp, content_type)
    assert(resp)
    assert(content_type)

    local contentType = resp.headers["Content-Type"]
    if contentType then
      local match, _ = ngx.re.match(contentType, '\\s*('..content_type..')\\s*;?', 'ixjo')
      if match then
        return true
      end
    end
    return false
  end

  --[[
    arguments
      resp {
        status  (number) : The resonse status, e.g. 200
        headers (table)  : A Lua table with response headers.
        body    (string) : The plain response body
      }
    return
      decoder  (ContentDecoder)
  ]]
  function _M.get_content_decoder(resp)
    local encoding = resp.headers['Content-Encoding']
    if encoding then
      local decoder = ContentDecoders[encoding]
      return decoder
    end
    return require("cjson.safe")
  end

  function _M.say_and_close(body)
    ngx.header.connection = "close"
    ngx.say(body)
    ngx.exit(ngx.OK)
    --主动断开链接
    --ngx.eof()
  end

end
return _M